package mvc.iogui.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFileChooser;

import mvc.iogui.IFileChooser;

public class LocalFileChooser extends JFileChooser implements IFileChooser {
	private static final long serialVersionUID = 1L;
	private DialogType dialogType;

	public enum DialogType {
		OPEN_DIALOG, SAVE_DIALOG
	}

	public LocalFileChooser() {
		throw new UnsupportedOperationException("Not implemented"); //$NON-NLS-1$
	}

	public LocalFileChooser(DialogType dt) {
		super();
		this.dialogType = dt;
	}

	private void setupOpen(List<String> acceptedFileExtensions) {
		this.setAcceptAllFileFilterUsed(false);
		this.setMultiSelectionEnabled(true);
		this.setFileFilter(new SimpleFileFilter(acceptedFileExtensions));
		this.setDialogType(OPEN_DIALOG);
		this.setFileSelectionMode(FILES_ONLY);

	}

	private void setupSave(List<String> acceptedFileExtensions) {
		this.setMultiSelectionEnabled(false);
		this.setAcceptAllFileFilterUsed(false);
		this.setDialogType(SAVE_DIALOG);
		for (String s : acceptedFileExtensions) {
			if (s != null && s.length() > 1) {
				this.addChoosableFileFilter(new SimpleFileFilter(s));
			}
		}
		this.setFileSelectionMode(DIRECTORIES_ONLY);
	}

	@Override
	public boolean showFileChooser(List<String> afe) {
		int result;
		if (dialogType == DialogType.OPEN_DIALOG) {
			setupOpen(afe);
			result = this.showOpenDialog(null);
		} else if (dialogType == DialogType.SAVE_DIALOG) {
			setupSave(afe);
			result = this.showSaveDialog(null);
		} else {
			return false;
		}
		if (result == JFileChooser.APPROVE_OPTION) {
			return true;
		}
		return false;
	}

	@Override
	public File getFile() {
		return this.getSelectedFile();
	}

	@Override
	public List<File> getFiles() {
		List<File> list = new ArrayList<File>();
		if (this.getSelectedFiles().length == 0) {
			list.add(this.getSelectedFile());
		} else {
			list = Arrays.asList(this.getSelectedFiles());
		}
		return list;
	}

	@Override
	public String getFileExtension() {
		return this.getFileFilter().getDescription().substring(1,
				this.getFileFilter().getDescription().length() - 1);
	}

}
